package com.jy.bo.common.conf.util;

import java.util.List;

/**
 * @program: binary-option
 * @description
 * @author: binary
 * @create: 2020-06-30 16:20
 **/
public class SearchUtils {

    /**
     * 二分查找目标值最接近的值
     *
     * @param array
     * @param targetNum
     * @return
     */
    public static Long binarySearchKey(Object[] array, Long targetNum) {
        int left = 0, right = 0;
        for (right = array.length - 1; left != right; ) {
            int midIndex = (right + left) / 2;
            int mid = (right - left);
            Long midValue = (Long) array[midIndex];
            if (targetNum.equals(midValue)) {
                return midValue;
            }
            if (targetNum > midValue) {
                left = midIndex;
            } else {
                right = midIndex;
            }
            if (mid <= 1) {
                break;
            }
        }
        Long rightNum = ((Long) array[right]);
        Long leftNum = ((Long) array[left]);
        return Math.abs((rightNum - leftNum) / 2) > Math.abs(rightNum - targetNum) ? rightNum : leftNum;
    }

    /**
     * 查找最接近的时间左值
     *
     * @param timestampList
     * @param timestamp
     * @return
     */
    public static Long binarySearchSettlementTime(List<Long> timestampList, Long timestamp) {
        if (timestampList == null || timestampList.size() == 0) {
            return null;
        }
        for (int i = timestampList.size() - 1; i >= 0; i--) {
            Long tmp = timestampList.get(i);
            if (tmp <= timestamp) {
                return tmp;
            }
        }
        return null;
    }

}
